package com.huan.groovy.service.impl;

import com.huan.groovy.utils.GroovyUtils;
import com.huan.groovy.service.UserService;
import com.huan.groovy.vo.AddUserRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.groovy.util.Maps;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * 用户service
 *
 * @author huan.fu
 * @date 2024/7/17 - 12:19
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private GroovyUtils groovyUtils;

    @Override
    public boolean existUserName(String username) {
        boolean exists = Objects.equals(username, "张三");
        log.info("验证用户: {} 是否存在? 存在?{}", username, exists);
        return exists;
    }

    @Override
    public String addUser(AddUserRequest request) throws URISyntaxException, IOException {
        // 此处的脚本可以从数据库中获取
        StopWatch stopWatch = new StopWatch("start");
        stopWatch.start();

        // 加载脚本内容
        String scriptPath = "/Users/huan/code/IdeaProjects/me/spring-cloud-parent/script-language/groovy-springboot/src/main/java/com/huan/groovy/script/ValidateScript.groovy";
        byte[] bytes = Files.readAllBytes(Paths.get(scriptPath));
        String script = new String(bytes);

        String result = groovyUtils.exec(script, Maps.of("param", request, "userService", this));
        stopWatch.stop();
        log.info(stopWatch.getTotalTimeMillis() + " ms");
        return result;
    }
}
